package com.qf.electronic.mall.register.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.qf.constant.RabbitConstant;
import com.qf.constant.RedisConstant;
import com.qf.dto.EmailMessageDto;
import com.qf.dto.ResultBean;
import com.qf.entity.TUser;
import com.qf.mapper.TUserMapper;
import com.qf.register.api.IRegisterService;
import com.qf.util.SpringSecurityUtil;
import com.qf.util.StringUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Value("${activeAccountServer}")
    String activeAccountServer;
    @Autowired
    private RedisTemplate redisTemplate;


    //邮箱注册
    @Override
    public ResultBean registerByEmail(String email, String password) {
        try{
            //1.发邮件
            EmailMessageDto message = new EmailMessageDto();
            message.setEmail(email);
            //生成uuid
            String uuid = UUID.randomUUID().toString();
            //创建url
            String url= activeAccountServer+uuid;
            message.setUrl(url);
            rabbitTemplate.convertAndSend(RabbitConstant.EMAIL_TOPIC_EXCHANGE,"email.register",message);
            //2.将数据插入到数据库中
            TUser user = new TUser();
            user.setEmail(email);
            user.setPassword(SpringSecurityUtil.getEncodePassword(password));
            tUserMapper.insertSelective(user);
            //3.存入到redis中
            //组织键
            String redisKey = StringUtil.getRedisKey(RedisConstant.REGISTER_EMAIL, uuid);
            redisTemplate.opsForValue().set(redisKey,email,15, TimeUnit.MINUTES);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.fail("注册失败");
        }
            return ResultBean.ok("注册成功");
    }



    //手机号注册
    @Override
    public ResultBean registerByphone(String phone, String code, String password) {
        //校验验证码
        String redisKey = StringUtil.getRedisKey(RedisConstant.REGISTER_PHONE, phone);
        String redisCode = (String)redisTemplate.opsForValue().get(redisKey);
        if(code.equals(redisCode)){
            TUser user = new TUser();
            user.setPassword(SpringSecurityUtil.getEncodePassword(password));
            user.setPhone(phone);
            int i = tUserMapper.insertSelective(user);
            if(i>0){
                return ResultBean.ok("注册成功");
            }else{
                return ResultBean.fail("注册失败");
            }

        }
        return ResultBean.fail("验证码错误");
    }
}
